#include"client.hpp"

void Usage()
{
  cout << "\n\t./client ServerIp SeverPort" << endl;
}

int main(int argc,char* argv[])
{
  if(argc != 3)
  {
    Usage();
    exit(USAGE_ERR);
  }
  string Ip = argv[1];
  uint16_t Port = atoi(argv[2]);
  //string Ip = "43.138.163.136";
  //uint16_t Port = 8081;

  int _socket = socket(AF_INET,SOCK_DGRAM,0);
  if(_socket == -1)
  {
    cerr << "create socket fail" << endl;
    exit(SOCKET_ERR);
  }
  cout << "create socket success" << endl;

  //明确server
  struct sockaddr_in peer;
  memset(&peer,0,sizeof(peer));
  peer.sin_family = AF_INET;
  peer.sin_port = htons(Port);//主机序列转网络序列，修正大小端问题
  peer.sin_addr.s_addr = inet_addr(Ip.c_str());//该函数作用 1.将点分十进制字符串转为int 2.主机序列转为网络序列
 
  cout << "sin_family : " << AF_INET << " sin_port : " << peer.sin_port << " s._addr " << inet_addr(Ip.c_str()) << endl;

  while(true)
  {
    string buffer;
    cout << "模拟服务器 : ";
    getline(cin,buffer);

    sendto(_socket,buffer.c_str(),buffer.size(),0,(struct sockaddr*)&peer,sizeof(peer));//sento表示发送，这里的peer是用来明确发送给谁的
    
    char str[1024];
    struct sockaddr_in tmp;
    socklen_t len = sizeof(tmp);
    int n = recvfrom(_socket,str,sizeof(str) - 1,0,(struct sockaddr*)&tmp,&len);//recvfrom是接收，这里的tmp是用来明确谁发给我的
    if(n != 0)
      str[n] = '\0';
    else
      continue;

    cout << "模拟服务器发来信息 : " << str << endl;
  }
  return 0;
}


